<template>
  <div>
    <div class="step_box">
      <el-steps :active="active" finish-status="success">
        <el-step title="基础信息"></el-step>
        <el-step title="规格信息"></el-step>
        <el-step title="商品展示"></el-step>
      </el-steps>
    </div>
    
    <!--基础信息-->
    <el-row v-show="active === 0" class="form_box">
      <el-col :span="18">
        <el-form ref="elForm1" :model="formData" :rules="rules" size="default" label-width="120px">
          <el-form-item label="商品类型" prop="prodType">
            <el-radio-group v-model="formData.prodType" size="default" style="width:600px;">
              <el-radio v-for="(item, index) in prodTypeOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品名称" prop="productName">
            <el-input v-model="formData.productName" placeholder="请输入商品名称" clearable :maxlength="40" show-word-limit :style="{width: '600px'}"></el-input>
          </el-form-item>
          <el-form-item label="商品简述" prop="intro">
            <el-input v-model="formData.intro" placeholder="请输入商品简述" clearable :maxlength="40" show-word-limit :style="{width: '600px'}"></el-input>
          </el-form-item>
          <el-form-item label="计量单位" prop="unitName">
            <el-input v-model="formData.unitName" placeholder="请输入计量单位" clearable :style="{width: '120px'}"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="typeIdList">
            <span style="margin-right: 10px;">暂未选择商品分类</span>
            <el-button type="primary" size="medium" @click="onOpen">选择分类 </el-button>
          </el-form-item>
          <el-form-item size="default">
            <el-button @click="resetForm">返回</el-button>
            <el-button type="primary" @click="submitForm">保存，下一步</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    
    <!--规格信息-->
    <el-row v-show="active === 1" class="form_box">
      <el-col :span="18">
        <el-form ref="elForm2" :model="formData2" size="default" >
          <el-form-item label="规格类型" prop="specType">
            <el-radio-group v-model="formData2.specType" size="default" style="width:600px;">
              <el-radio :value="1" >单规格</el-radio>
              <el-radio :value="2" >多规格</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-col>
      
      <el-col :span="18">
        <el-table :data="specList" :max-height="400" size="default">
          <el-table-column label="规格组" min-width="30">
            <template #default="{ row, $index }">
              <span>{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="30">
            <template #default="{ $index }">
              <a @click="deletespecList($index)">删除</a>
            </template>
          </el-table-column>
          <el-table-column label="规格名称" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.specName" placeholder="请输入规格名称" :maxlength="10" show-word-limit size="default" min-width="130"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="规格值" min-width="160">
            <template #default="{ row, $index }">
              <el-input v-model="row.value" placeholder="请输入规格值" :maxlength="50" size="default" :inputStyle="{paddingRight:0}">
              <el-button type="primary" @click="addSkuOption($index)" size="default" style="width:100%">添加</el-button>
              </el-input>
              <div v-if="row.itemList.length" style="margin: 10px 0;">
                <el-tag v-for="(item2, i2) in row.itemList" closable @close="deleteSkuOption($index, i2)" size="default" :key="i2" style="margin-right: 10px;">{{item2}}</el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" @click="addspecList" style="margin:10px 0;">添加规格</el-button>
      </el-col>
      
      <el-col :span="18">
        <el-table :data="skuList" :max-height="400" size="default">
          <el-table-column label="编号" min-width="30">
            <template #default="{ $index }">
              <span>{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="30">
            <template #default="{ $index }">
              <a @click="deleteSku($index)">删除</a>
            </template>
          </el-table-column>
          <el-table-column label="主图" min-width="60">
            <template #default="{ row }">
              <el-upload class="img-upload-mini" :action="uploadUrl" list-type="picture-card">
                <i class="el-icon-plus"></i>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="规格" min-width="120">
            <template #default="{ row }">
              {{ row.wholeName }}
            </template>
          </el-table-column>
          <el-table-column label="SKU名称" min-width="130">
            <template #default="{ row }">
              <el-input v-model="row.skuName" placeholder="请输入SKU名称" :maxlength="40" size="default" min-width="130"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品编号" min-width="130" required>
            <template #default="{ row }">
              <el-input v-model="row.platId" placeholder="请输入商品编号" :maxlength="40" size="default" min-width="130"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="条形码" min-width="130">
            <template #default="{ row }">
              <el-input v-model="row.barcode" placeholder="请输入条形码" :maxlength="40" size="default" min-width="130"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="成本价（元）" min-width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.skuName" placeholder="请输入成本价" :precision="2" :step="0.1" :maxlength="40" size="default" min-width="130"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="重量（kg）" min-width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.weight" placeholder="请输入重量" :precision="2" :step="0.1" :maxlength="40" size="default" min-width="130"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" style="margin:10px 0;">重置商品</el-button>
      </el-col>
    </el-row>
    
    <SelectCategory :dialogVisible="dialogVisible" @onOk="onOk" @onClose="dialogVisible = false"></SelectCategory>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import SelectCategory from '@/components/SelectCategory'
import { getSpecId } from "@/api/goods";

const { proxy } = getCurrentInstance();
// 状态管理
const dialogVisible = ref(false)
const specList = ref([])
const skuList = ref([])
const active = ref(1)
const formData = reactive({
  prodType: 1,
  productName: undefined,
  intro: undefined,
  unitName: undefined,
  typeIdList: undefined,
})

const rules = reactive({
  prodType: [],
  productName: [{
    required: true,
    message: '请输入商品名称',
    trigger: 'blur'
  }],
  intro: [],
  unitName: [{
    required: true,
    message: '请输入计量单位',
    trigger: 'blur'
  }],
})

const prodTypeOptions = ref([{
  "label": "实体商品（物流发货）",
  "value": 1
}, {
  "label": "虚拟商品（无需发货）",
  "value": 2
}])

const formData2 = reactive({
  specType: 1
})


const uploadUrl = ref('https://example.com/upload') // 示例上传URL

// DOM引用
const elForm1 = ref(null)
const elForm2 = ref(null)

// 生命周期钩子
onMounted(() => {
  // 初始化逻辑
})

// 方法
const submitForm = () => {
  elForm1.value.validate(valid => {
    if (!valid) return
    // TODO 提交表单
    next()
  })
}

const resetForm = () => {
  elForm1.value.resetFields()
}

const next = () => {
  if (active.value++ > 2) active.value = 0
}

const onOpen = () => {
  dialogVisible.value = true
}

const onOk = (data) => {
  console.log(112, data)
  dialogVisible.value = false
}

// 添加规格
const addspecList = async () => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  let res = await getSpecId()
  console.log(res.data)
  newspecList.push({
    id:res.data,
    specName: '',
    value: '',
    sortNum:newspecList.length+1,
    delFlag:0,
    itemList: []
  })
  specList.value = newspecList
  getSkuList(newspecList)
}

const deletespecList = (idx) => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  newspecList.map((item,i)=>{
    if(i==idx){
      item.delFlag = 1
    }
  })
  specList.value = newspecList
  getSkuList(newspecList)
}

// 添加规格值
const addSkuOption = (index) => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  
  if (!newspecList[index]?.value) {
    proxy.$modal.msgError(`请输入规格值!`)
    return
  }
  
  if (newspecList[index]?.itemList) {
    newspecList[index].itemList.push(newspecList[index].value)
  } else {
    newspecList[index].itemList = [newspecList[index].value]
  }
  
  newspecList[index].value = ''
  specList.value = newspecList
  getSkuList(newspecList)
}

// 删除规格值
const deleteSkuOption = (i1, i2) => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  newspecList[i1].itemList = newspecList[i1].itemList.filter((_, i) => i !== i2)
  specList.value = newspecList
  getSkuList(newspecList)
}

const deleteSku = (idx) => {
  skuList.value = skuList.value.filter((_, i) => i !== idx)
}

// 生成SKU组合
const getSkuList = (attrList) => {
  let skus = []
  const skuMap = new Map()
  
  if (skuList.value) {
    skuList.value.forEach(sku => {
      skuMap.set(sku.spData, sku)
    })
  }
  console.log(111,skuMap)
  attrList.forEach((attr, index) => {
    const attrSku = []
    
    attr.itemList.forEach(specName => {
      if (!specName) {
        return
      }
      
      if (index === 0) {
        attrSku.push({ [attr.specName]: specName })
      } else {
        skus.forEach(it3 => {
          attrSku.push({ ...it3, [attr.specName]: specName })
        })
      }
    })
    
    skus = attrSku
  })
  
  skus.forEach(it => {
    if (it) {
      console.log(3,it)
      let objStr = JSON.parse(JSON.stringify(it))
      it.spData = JSON.stringify(it)
      let wholeName = ''
      let specIdList = []
      for(let item in objStr){
        specIdList.push(objStr[item])
      }
      it.wholeName=specIdList.join(' ')
      it.specIdList = specIdList
    }
  })
  
  skus.forEach(it => {
    const sku = skuMap.get(it.spData)
    console.log(6,sku,it)
    if (sku) {
      it.barcode = sku.barcode
      it.delFlag = sku.delFlag
      it.img = sku.img
      it.outerId = sku.outerId
      it.platId = sku.platId
      it.skuName = sku.skuName
      it.specIdList = sku.specIdList
      it.weight = sku.weight
      it.wholeName = sku.wholeName
      it.id = sku.id
    } else {
      it.barcode = null
      it.delFlag = 0
      it.img = null
      it.outerId = null
      it.platId = null
      it.skuName = null
      it.weight = null
      // it.specIdList = sku.specIdList
      // it.wholeName = sku.wholeName
      it.id = null
    }
  })
  console.log(11,skus,attrList,skuMap)
  if(skus.length==0 && attrList.length!=0)return
  skuList.value = skus
}
</script>

<style lang="scss" scoped>
::v-deep .el-upload--picture-card{
  width:44px;
  height:44px;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep .el-step__title{
    font-size: 14px;
  }
.step_box{
  width: 70%;
  margin: 60px auto 0;
  
}
.form_box{
  display: flex;
  justify-content: center;
  padding-top: 40px;
  flex-wrap: wrap;
}
</style>